$.ajaxSetup({  
    contentType:"application/x-www-form-urlencoded;charset=utf-8",  
    complete:function(XMLHttpRequest,textStatus){
          var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus");
          var permissonStatus=XMLHttpRequest.getResponseHeader("permissonStatus");
          var contextPath = XMLHttpRequest.getResponseHeader("contextPath");
          if(sessionstatus=="timeout"){
        	  redirectLogin(contextPath);
          }  
          
          if(permissonStatus == "nopermission"){
        	  try{
        		  $(this).alertmsg("warn","您无权访问该页面，请您联系管理员，稍后再试!",{
              	    displayPosition : 'middlecenter'
              	  }); 
        	  } catch(e){
        		  console.log("nopermission");
        	  }
          } else if(permissonStatus == "firstLogin"){
        	  window.location.href = contextPath + XMLHttpRequest.getResponseHeader("firstLoginUrl");
          }
    },
    "error":myError
});

function redirectLogin(contextPath){
	//跳转的登录页面  
	if (window.top != window) {
		window.top.location.href= contextPath + "/login.html";
	} else {
		window.location.href= contextPath + "/login.html";
	}
}

function myError(XMLHttpRequest, textStatus, errorThrown) {
	var contextPath = XMLHttpRequest.getResponseHeader("contextPath");
	if(XMLHttpRequest.status==403){
		//跳转的登录页面  
		if (window.top != window) {
			window.top.location.href= contextPath + "/login.html";
		} else {
			window.location.href= contextPath + "/login.html";
		}
	}else if(XMLHttpRequest.status==500){
		window.location.href = contextPath +  "/error500.jsp";
	}else if(XMLHttpRequest.status==408){
		window.location.href = contextPath +  "/error408.jsp";
	}else if(XMLHttpRequest.status==406){
		window.location.href = contextPath +  "/error406.jsp";
	}else if(XMLHttpRequest.status==404){
		window.location.href = contextPath +  "/error404.jsp";
	}
}

function setForm(jsonData, $form, callback) {
	$.each(jsonData, function(_name, _val){
		$inputObj = $form.find("input:[name=" + _name + "]");
		$spanObj = $form.find("span:[name=" + _name + "]");
		$textareaObj = $form.find("textarea:[name=" + _name + "]");
		if($inputObj && $inputObj.length != 0){
			$inputObj.val(_val);
		} else if($spanObj && $spanObj.length != 0) {
			$spanObj.html(_val);
		} else if($textareaObj && $textareaObj.length != 0) {
			$textareaObj.val(_val);
		} else {
			$inputObj = $form.find("select:[name=" + _name + "]");
			if($inputObj && $inputObj.length != 0){
				$inputObj.selectpicker('val', ''+_val).trigger("change");;
			}
		}
		
		if(callback){
			callback($inputObj, _name, _val);
		}
	});
}
function setLook(jsonData, $form, callback) {
	$.each(jsonData, function(_name, _val){
		$inputObj = $form.find("input:[name=" + _name + "]");
		$spanObj = $form.find("span:[name=" + _name + "]");
		$textareaObj = $form.find("textarea:[name=" + _name + "]");
		if($inputObj && $inputObj.length != 0){
			$inputObj.val(_val);
		} else if($spanObj && $spanObj.length != 0) {
			$spanObj.html(_val);
		} else if($textareaObj && $textareaObj.length != 0) {
			$textareaObj.val(_val);
		} else {
			$inputObj = $form.find("select:[name=" + _name + "]");
			if($inputObj && $inputObj.length != 0){
				$inputObj.selectpicker('val', ''+_val).trigger("change");;
			}
		}
		
		if(callback){
			callback($inputObj, _name, _val);
		}
	});
}

function getJsonData2Form(url, param, $form, callback, failCallback){
	var isSuccess = false;
	$.ajax({
		type     : 'POST',
		async    : false,
		dataType : 'json',
		url      : url,
		data     : param,
		cache    : false,
		success  : function(json) {
			if(json){
				if(json.resultCode == 'success'){
					if(json.data){
						setForm(json.data[0], $form, callback);
					}
					isSuccess = true;
				} else {
					if (failCallback) {
						failCallback(json);
					} else {
						$form.alertmsg('info', json.message);
					}
				}
			}
		},
		error   : BJUI.ajaxError
	});
	return isSuccess;
}

function getJsonData2Look(url, param, $form, callback){
	var isSuccess = false;
	$.ajax({
		type     : 'POST',
		async    : false,
		dataType : 'json',
		url      : url,
		data     : param,
		cache    : false,
		success  : function(json) {
			if(json){
				if(json.resultCode == 'success'){
					if(json.data){
						setLook(json.data[0], $form, callback);
					}
					isSuccess = true;
				} else {
					$form.alertmsg('info', json.message);
				}
			}
		},
		error   : BJUI.ajaxError
	});
	return isSuccess;
}

function getFileSize(obj) {
    var size = 0;  
    if(navigator.userAgent.indexOf("MSIE")>0){    
        var fso = new ActiveXObject('Scripting.FileSystemObject');  
        var file = fso.GetFile(obj.value);  
        size = file.size;   
    }else {  
        size = obj.files[0].size;  
    }  
    return size;
}

function myAjax(url, data, async, successCallBack, failCallBack, errorCallBack) {
	if(async == null || async == 'undefined') async = true;
	$(document.body).showLoading();
	$.ajax({
		url     : url,
		type    : "post",
		async   : async,
		dataType: "json",
		data    : data,
		success : function(result){
			$(document.body).hideLoading();
			if(result){
				if("success"==result.resultCode){
					if(successCallBack){
						successCallBack(result);
					}
				}else{
					if(failCallBack){
						failCallBack(result);
					} else {
						$(document.body).alertmsg('error', result.message);
					}
				}
			}
		},
		error: function(xhr, ajaxOptions, thrownError) {
			$(document.body).hideLoading();
			if(errorCallBack){
				errorCallBack(xhr, ajaxOptions, thrownError);
			} else {
				$(document.body).bjuiajax('ajaxError', xhr, ajaxOptions, thrownError);
			}
		}
	});
}

/**
 * 日期对象转换为指定格式的字符串
 * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
 * @param date Date日期对象, 如果缺省，则为当前时间
 *
 * YYYY/yyyy/YY/yy 表示年份  
 * MM/M 月份  
 * W/w 星期  
 * dd/DD/d/D 日期  
 * hh/HH/h/H 时间  
 * mm/m 分钟  
 * ss/SS/s/S 秒  
 * @return string 指定格式的时间字符串
 */
function dateToStr(formatStr, date){
    formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
    date = arguments[1] || new Date();
    var str = formatStr;   
    var Week = ['日','一','二','三','四','五','六'];  
    str=str.replace(/yyyy|YYYY/,date.getFullYear());   
    str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));   
    str=str.replace(/MM/,date.getMonth()>=9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));   
    str=str.replace(/M/g,(date.getMonth()+1));   
    str=str.replace(/w|W/g,Week[date.getDay()]);   
   
    str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());   
    str=str.replace(/d|D/g,date.getDate());   
   
    str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());   
    str=str.replace(/h|H/g,date.getHours());   
    str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());   
    str=str.replace(/m/g,date.getMinutes());   
   
    str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());   
    str=str.replace(/s|S/g,date.getSeconds());   
   
    return str;   
}

/**
 * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
 * 
 */
function strToDate(formatStr, dateStr){
	formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
     var year = 0;
     var start = -1;
     var len = dateStr.length;
     if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
         year = dateStr.substr(start, 4);
     }
     var month = 0;
     if((start = formatStr.indexOf('MM')) > -1  && start < len){
         month = parseInt(dateStr.substr(start, 2)) - 1;
     }
     var day = 0;
     if((start = formatStr.indexOf('dd')) > -1 && start < len){
         day = parseInt(dateStr.substr(start, 2));
     }
     var hour = 0;
     if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
         hour = parseInt(dateStr.substr(start, 2));
     }
     var minute = 0;
     if((start = formatStr.indexOf('mm')) > -1  && start < len){
         minute = dateStr.substr(start, 2);
     }
     var second = 0;
     if((start = formatStr.indexOf('ss')) > -1  && start < len){
         second = dateStr.substr(start, 2);
     }
     return new Date(year, month, day, hour, minute, second);
}

/**
 * 给日期加上指定天数
 * @param srcDate
 * @param days
 * @returns
 */
function addDayForDate(srcDate, days) {
	var retDate = null;
	if ((typeof srcDate) ==  'string') {
		var tempDate = strToDate('yyyy-MM-dd', srcDate);
		retDate = new Date(tempDate.getTime() + (86400000 * days));
	} else {
		retDate = new Date(srcDate.getTime() + (86400000 * days));
	}
	return retDate;
}

/**
 * 求两个时间的天数差
 * @param dateStart
 * @param dateEnd
 * @returns
 */
function daysBetween(dateStart,dateEnd) {
	var _startDate, _endDate;
	if ((typeof dateStart) ==  'string') {
		_startDate = strToDate('yyyy-MM-dd', dateStart);
	} else {
		_startDate = dateStart;
	}
	if ((typeof dateEnd) ==  'string') {
		_endDate = strToDate('yyyy-MM-dd', dateEnd);
	} else {
		_endDate = dateEnd;
	}
	return (_endDate.getTime() - _startDate.getTime()) / 86400000;
}

function clearLookUp(_this) {
	var $this = $(_this);
	$this.parent().find('input').val('');
}